package com.inossem.warehousestorage_inossem.activity.out_storage;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.inossem.loadandrefresh.PullToRefreshLayout;
import com.inossem.loadandrefresh.pullableview.PullableListView;
import com.inossem.utils.base.QRCodeUtils;
import com.inossem.utils.constant.QRCodeConstant;
import com.inossem.utils.listener.NoDoubleClickListener;
import com.inossem.warehousestorage_inossem.R;
import com.inossem.warehousestorage_inossem.activity.base.BaseActivity;
import com.inossem.warehousestorage_inossem.activity.out_storage.extra.OutStorageExtra;
import com.inossem.warehousestorage_inossem.adapter.outStorage.AllocatingOutStorageDetailListAdapter;
import com.inossem.warehousestorage_inossem.bean.outStorage.BatchBean;
import com.inossem.warehousestorage_inossem.bean.outStorage.OutStorageAllocatingOverviewBean;
import com.inossem.warehousestorage_inossem.bean.outStorage.OutStorageCalculatorBean;
import com.inossem.warehousestorage_inossem.constant.TypeEnum;
import com.inossem.warehousestorage_inossem.dialog.DialogUtils;
import com.inossem.warehousestorage_inossem.listener.GsonBeanListener;
import com.inossem.warehousestorage_inossem.listener.OutStorageDetailListener;
import com.inossem.warehousestorage_inossem.request.outStorage.GetDefaultBatchRequest;
import com.inossem.warehousestorage_inossem.request.outStorage.OutStorageCalculatorRequest;
import com.inossem.warehousestorage_inossem.utils.ActivityUtils;
import com.inossem.warehousestorage_inossem.utils.OutStorageUtils;

import java.math.BigDecimal;
import java.util.List;

/**
 * 作者：wsy on 2017/12/5 10:52
 * <p>
 * 邮箱：445979770@qq.com
 */

public class OutStorageAllocatingDetailActivity extends BaseActivity {

    private TextView title;

    private PullToRefreshLayout refresh;

    private PullableListView allocatingOutStorageDetailList;

    private AllocatingOutStorageDetailListAdapter adapter;

    private String mSerial, mBatchNumber, mPickingClassify, mUseDepartment, materielCode, mRetainDecimal;

    private OutStorageAllocatingOverviewBean.BodyBean.ItemListBean mMaterielDetail;

    @Override
    protected void onCreateImpl(Bundle savedInstanceState) {
        setContentView(R.layout.activity_out_storage_allocating_detail);
        initView(OutStorageAllocatingDetailActivity.this);
    }

    @Override
    protected void onResumeImpl() {
        initData(OutStorageAllocatingDetailActivity.this);
    }

    private void initView(Activity activity) {
        title = (TextView) activity.findViewById(R.id.headerTitle);
        allocatingOutStorageDetailList = (PullableListView) activity.findViewById(R.id.allocatingOutStorageDetailList);
        refresh = (PullToRefreshLayout) activity.findViewById(R.id.allocatingOutStorageDetailRefresh);
    }

    private void initData(Activity activity) {
        title.setText(getResources().getString(R.string.activity_out_storage_allocating_detail_in_allocating_the_detail));
        ActivityUtils.initBackAndFunction(activity, getResources().getString(R.string.activity_out_storage_allocating_add_operator_allocating_an_overview), new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                String message = check(activity);
                if (message != null) {
                    DialogUtils.getConfirmDialog(OutStorageAllocatingDetailActivity.this, message, new DialogUtils.ConfirmDialogListener() {
                        @Override
                        public void onConfirm(Dialog dialog) {
                            OutStorageAllocatingDetailActivity.this.finish();
                        }
                    }).show();
                } else {
                    updateInfo(OutStorageAllocatingDetailActivity.this);
                    OutStorageAllocatingDetailActivity.this.finish();
                }
            }
        });

        allocatingOutStorageDetailList.setPullUpFlag(false);
        allocatingOutStorageDetailList.setPullDownFlag(false);
        mBatchNumber = "";
        getExtra(activity);
        getData(activity);
        setmScanListener((String scanResult, int length) -> {
            String type = QRCodeUtils.getQRCodeType(scanResult);
            switch (type) {
                case QRCodeConstant.TYPE_BATCH:
                    adapter.addBatchRequest(activity, false, null, QRCodeUtils.DecryptQRCode(scanResult, QRCodeConstant.PARAMETER_BATCH_NUMBER));
                    break;
                case QRCodeConstant.TYPE_POSITION:
                    adapter.addBatchRequest(activity, false, null, QRCodeUtils.DecryptQRCode(scanResult));
                    break;
            }
        }, QRCodeConstant.TYPE_BATCH, QRCodeConstant.TYPE_POSITION);
    }

    private void getCalculator(Context context) {
        OutStorageCalculatorRequest.request(context, materielCode, new GsonBeanListener<OutStorageCalculatorBean>() {
            @Override
            public void onSuccess(OutStorageCalculatorBean bean) {
                if (bean.getData().getFlag().equals("0")) {
                    Toast.makeText(context, getResources().getString(R.string.activity_out_storage_allocating_detail_can_not_use_calculator), Toast.LENGTH_SHORT).show();
                } else {
                    DialogUtils.getCalculatorDialog(context, bean).show();
                }

            }
        });
    }

    private void getExtra(Activity activity) {
        mSerial = activity.getIntent().getStringExtra(OutStorageExtra.SERIAL);
//        mPickingClassify = activity.getIntent().getStringExtra(OutStorageExtra.PICKING_CLASSIFY);
//        mUseDepartment = activity.getIntent().getStringExtra(OutStorageExtra.USE_DEPARTMENT);
//        sendFactoryCode =  activity.getIntent().getStringExtra(OutStorageExtra.SEND_FACTORY_CODE);
//        sendLocationgCode =  activity.getIntent().getStringExtra(OutStorageExtra.SEND_LOCATION_CODE);
    }

    private void addOutStoragePickingItemListData(Context context, OutStorageAllocatingOverviewBean.BodyBean.ItemListBean materielDetail, List<BatchBean.BatchInfoBean> batchList, String batchNumber, ListView listView) {
        adapter = new AllocatingOutStorageDetailListAdapter(context, materielDetail, batchList, batchNumber, new OutStorageDetailListener() {

            @Override
            public void getDefaultBatch(String number) {
                GetDefaultBatchRequest.request(context, mMaterielDetail.getMat_id(), number, mMaterielDetail.getLocation_id(), null, TypeEnum.OUT_STORAGE_ALLOCATING, new GsonBeanListener<BatchBean>() {
                    @Override
                    public void onSuccess(BatchBean bean) {
                        addOutStoragePickingItemListData(context, mMaterielDetail, bean.getBody(), "", allocatingOutStorageDetailList);
                    }
                });
            }

            @Override
            public void selectItem(int position) {
                allocatingOutStorageDetailList.setSelection(position);
            }

            @Override
            public void calculator() {
                getCalculator(OutStorageAllocatingDetailActivity.this);
            }
        });
        listView.setAdapter(adapter);
    }

    private void getData(Context context) {
        mMaterielDetail = OutStorageUtils.getAllocatingOutStorageDetailBySerial(context, mSerial);
        materielCode = mMaterielDetail.getMat_code();
        mRetainDecimal = mMaterielDetail.getDecimal_place();
        addOutStoragePickingItemListData(context, mMaterielDetail, mMaterielDetail.getBatchList(), mBatchNumber, allocatingOutStorageDetailList);
    }

    @Override
    public void onBackPressed() {
        String message = check(OutStorageAllocatingDetailActivity.this);
        if (message != null) {
            DialogUtils.getConfirmDialog(OutStorageAllocatingDetailActivity.this, message, new DialogUtils.ConfirmDialogListener() {
                @Override
                public void onConfirm(Dialog dialog) {
                    OutStorageAllocatingDetailActivity.super.onBackPressed();
                }
            }).show();
        } else {
            updateInfo(OutStorageAllocatingDetailActivity.this);
            OutStorageAllocatingDetailActivity.super.onBackPressed();
        }
    }

    private void updateInfo(Context context) {
        mMaterielDetail.setBatchList(adapter.getmBatchList());
        mMaterielDetail.setActualSendNumber(adapter.getmActualSendNumber());
//        OutStorageUtils.updateAllocatingOutStorageDetail(context, mMaterielDetail);
    }

    private String check(Context context) {
        String message;
//        message = checkCount();
//        if (message != null) {
//            return message;
//        }
        message = OutStorageUtils.checkConfirm(context, adapter.getmBatchList());
        if (message != null) {
            return message;
        }
        message = OutStorageUtils.checkNumber(context, adapter.getmBatchList());
        if (message != null) {
            return message;
        }
        message = OutStorageUtils.checkRetainDecimal(context, adapter.getmBatchList(), mRetainDecimal);
        if (message != null) {
            return message;
        }
        message = OutStorageUtils.checkCanSendNumber(context, adapter.getmActualSendNumber(), mMaterielDetail.getLast_qty());
        if (message != null) {
            return message;
        }
        message = checkAllSend(context, adapter.getmActualSendNumber(), mMaterielDetail.getLast_qty());
        if (message != null) {
            return message;
        }
        return message;
    }

    //调拨出库数量必须等于可发数量，高海涛
    private String checkAllSend(Context context, String actualSendNumber, String canSendNumber) {
        if (!TextUtils.isEmpty(actualSendNumber)) {
            BigDecimal actualSendNumberBigDecimal = new BigDecimal(actualSendNumber);
            BigDecimal canSendNumberBigDecimal = new BigDecimal(canSendNumber);
            if (actualSendNumberBigDecimal.compareTo(canSendNumberBigDecimal) != 0) {
                return context.getResources().getString(R.string.activity_out_storage_sale_detail_all_send_equal);
            }
        }
        return null;
    }
//
//    private String checkCount() {
//        if (adapter == null || adapter.getCount() <= 1) {
//            return getResources().getString(R.string.activity_out_storage_allocating_detail_please_add_record);
//        }
//        return null;
//    }
//
//    private String checkConfirm() {
//        int count = adapter.getCount() - 1;
//        for (int i = 0; i < count; i++) {
//            OutStoragePickingBatchListBean.DataBean.BatchListBean batchItem = (OutStoragePickingBatchListBean.DataBean.BatchListBean) adapter.getItem(i);
//            if (!OutStorageUtils.CONFIRM.equals(batchItem.getIsConfirm())) {
//                return getResources().getString(R.string.activity_in_storage_allocating_overview_control) + (i + 1) + getResources().getString(R.string.activity_out_storage_sale_detail_have_not_been_confirmed);
//            }
//        }
//        return null;
//    }
//
//    private String checkNumber() {
//        int count = adapter.getCount() - 1;
//        for (int i = 0; i < count; i++) {
//            OutStoragePickingBatchListBean.DataBean.BatchListBean batchItem = (OutStoragePickingBatchListBean.DataBean.BatchListBean) adapter.getItem(i);
////            LogUtils.i("batchItem.getOutStorageNumber():" + batchItem.getOutStorageNumber());
//            if (TextUtils.isEmpty(batchItem.getOutStorageNumber()) || RegexUtils.checkZero(batchItem.getOutStorageNumber())) {
//                return getResources().getString(R.string.activity_in_storage_allocating_overview_control) + (i + 1) + getResources().getString(R.string.activity_out_storage_sale_detail_not_illegal);
//            }
//        }
//        return null;
//    }
//    private String checkRetainDecimal() {
//        int count = adapter.getCount() - 1;
//        for (int i = 0; i < count; i++) {
//            OutStoragePickingBatchListBean.DataBean.BatchListBean batchItem = (OutStoragePickingBatchListBean.DataBean.BatchListBean) adapter.getItem(i);
//            if (!TextUtils.isEmpty(batchItem.getOutStorageNumber()) &&!Utils.checkRetainDecimal(batchItem.getOutStorageNumber(), mRetainDecimal)) {
////            Utils.middleToast(context, context.getResources().getString(R.string.activity_in_storage_receive_overview_serial) + (i + 1) + );
//                return getResources().getString(R.string.activity_in_storage_receive_overview_serial) + (i + 1) +String.format(getResources().getString(R.string.common_retain_decimal_illegal), TextUtils.isEmpty(mRetainDecimal) ? getResources().getString(R.string.common_retain_decimal_unlimited) : mRetainDecimal);
//            }
//        }
//        return null;
//    }
}
